<?php

namespace app\admin\controller\xmwechat\offiaccount;

use app\common\controller\Backend;
use app\common\library\xmwechat\offiaccount\MaterialService;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Throwable;

/**
 * 微信公众号素材
 */
class Material extends Backend
{
    /**
     * Material模型对象
     * @var object
     * @phpstan-var \app\admin\model\xmwechat\offiaccount\Material
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id', 'type'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\xmwechat\offiaccount\Material;
        $this->request->filter('trim,htmlspecialchars');
    }

    public function index(): void
    {
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->param();
        if (!isset($params['type'])) {
            $search         = $this->request->get("search/a", []);
            $params['type'] = 'text';
            foreach ($search as $field) {
                if (!is_array($field) || !isset($field['operator']) || !isset($field['field']) || !isset($field['val'])) {
                    continue;
                }
                $val            = $field['val'];
                $field          = $field['field'];
                $params[$field] = $val;
            }
        }

        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        if ($params['type'] == 'text') {
            $res   = $this->model
                ->field($this->indexField)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->paginate($limit);
            $list  = $res->items();
            $total = $res->total();
        } else if ($params['type'] == 'news') {
            $page = $this->request->get('page');
            if (!isset($page)) $page = 1;
            $data  = MaterialService::getInstance()->getMaterialFreePublish($page, $limit);
            $list  = $data['list'];
            $total = $data['total'];
        } else {
            $page = $this->request->get('page');
            if (!isset($page)) $page = 1;
            $data  = MaterialService::getInstance()->getMaterialList($params['type'], $page, $limit);
            $list  = $data['list'];
            $total = $data['total'];
        }

        $this->success('', [
            'list'  => $list,
            'total' => $total,
        ]);
    }

    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $this->checkMaterial($data);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $materialData['content']   = $data['content'];
                $materialData['event_key'] = $this->generateRandomString(30);
                $materialData['type']      = $data['type'];
                $result                    = $this->model->save($materialData);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);

            $this->checkMaterial($data);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $materialData['content'] = $data['content'];
                $materialData['type']    = $data['type'];
                $result                  = $row->save($materialData);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    public function checkMaterial(array $data)
    {
        $type = $data['type'];
        if ($type == 'text') {
            if (empty($data['content'])) {
                $this->error('请填写内容');
            }
        }
    }

    public function select(): void
    {
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->param();
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $where['type'] = $params['type'];
        if ($params['type'] == 'text') {
            $res   = $this->model
                ->field($this->indexField)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->paginate($limit);
            $list  = $res->items();
            $total = $res->total();
        } else if ($params['type'] == 'news') {
            $page = $this->request->get('page');
            if (!isset($page)) $page = 1;
            $data  = MaterialService::getInstance()->getMaterialFreePublish($page, $limit);
            $list  = $data['list'];
            $total = $data['total'];
        } else {
            $page = $this->request->get('page');
            if (!isset($page)) $page = 1;
            $data  = MaterialService::getInstance()->getMaterialList($params['type'], $page, $limit);
            $list  = $data['list'];
            $total = $data['total'];
        }

        $this->success('', [
            'list'  => $list,
            'total' => $total,
        ]);
    }

    public function generateRandomString($length = 35): string
    {
        $characters      = '12356789abcdefghijklmnopqrstuvwxyz';
        $characterLength = strlen($characters);
        $randomString    = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $characterLength - 1)];
        }
        return $randomString;
    }


    /**
     * 获取已选中/添加的菜单内容
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMenuContent(): void
    {
        $params = $this->request->param();
        if (isset($params['key']) && !empty($params['key'])) {
            $content = $this->model->where('event_key', $params['key'])->where('type', 'text')->value('content');
            $data    = [
                'content' => $content
            ];
            $this->success('success', $data);
        }

        if (isset($params['media_id']) && !empty($params['media_id'])) {
            try {
                $data = MaterialService::getInstance()->getMaterialByMediaId($params['media_id']);
                $this->success('success', $data);
            } catch (ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) {
                $this->error($e->getMessage());
            }
        }

        if (isset($params['article_id']) && !empty($params['article_id'])) {
            try {
                $data = MaterialService::getInstance()->getMaterialByArticleId($params['article_id']);
                $this->success('success', $data);
            } catch (ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) {
                $this->error($e->getMessage());
            }
        }
        $this->success('success');
    }

}